<?php

namespace App\Http\Controllers\Weixin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\WxTemplateMessage;

class TemplateMessageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $perPage = $request->input('pageSize', 15);
        $data = WxTemplateMessage::paginate($perPage);
        return ['data' => $data, 'industry'=>config('wechat.industry')];
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $app = app('wechat.official_account');
        $list = $app->template_message->getPrivateTemplates();
        $templates = array_get($list, 'template_list', []);
        if(!$templates){
            $this->error('请先在微信公众号后台添加模板');
        }
        WxTemplateMessage::where('id', '>', 0)->delete();
        foreach ($templates as $vv) {
            WxTemplateMessage::create($vv);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $app = app('wechat.official_account');
        $industry = $request->input('industry', []);
        $message = [
            'industry.required' => '请选择行业',
            'industry.size' => '选择2个行业',
        ];
        $this->validate($request, [
            'industry'=>'required|size:2',
        ], $message);
        return $app->template_message->setIndustry(...$industry);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $template = WxTemplateMessage::findOrFail($id);
        if (!$template->delete()) {
            return $this->error('删除失败');
        }
        $app = app('wechat.official_account');
        $app->template_message->deletePrivateTemplate($template->template_id);
    }
}
